package com.hh.demo.exception;

import com.hh.demo.constants.ExceptionEnum;
import com.hh.demo.exception.GlobalException;
import com.hh.demo.result.JSONResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 黄浩
 * @create 2022-07-15 10:56
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 俺们自定义的异常
     * @param e
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public JSONResult globalException(GlobalException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),e.getCode());
    }


    /**
     * 除了自定义异常，其他的异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JSONResult exception(Exception e){
        e.printStackTrace();
        return JSONResult.error(ExceptionEnum.OTHER_EXCEPTION.getMessage(),ExceptionEnum.OTHER_EXCEPTION.getCode());
    }

    /**
     * JR303参数校验
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult JSR303ParamException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(err->{
            sb.append(err.getDefaultMessage()).append(";");
        });
        return JSONResult.error(sb.toString());
    }
}
